package cn.kgc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.base.SystemConstant;
import cn.kgc.entity.Company;
import cn.kgc.entity.Users;
import cn.kgc.excpetion.GraceException;
import cn.kgc.feign.UserFeignClient;
import cn.kgc.form.CompanyAddOrReviewForm;
import cn.kgc.form.CompanyAdminReviewForm;
import cn.kgc.form.CompanyHrReviewForm;
import cn.kgc.form.CompanyQueryForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.mapper.CompanyMapper;
import cn.kgc.service.CompanyService;
import cn.kgc.utils.PagedGridResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author YC
 */
@Slf4j
@Service("companyService")
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    @GlobalTransactional
    public boolean review(CompanyAdminReviewForm form) {
        // 无论是否同意，修改审批状态
        if (form.getReviewStatus() == SystemConstant.REVIEW_STATUS_REVIEW_FAIL) {
            this.update(new LambdaUpdateWrapper<Company>()
                    .eq(Company::getId, form.getCompanyId())
                    .set(Company::getReviewStatus, form.getReviewStatus())
                    .set(Company::getReviewReplay, form.getReviewReply())
            );
        }
        // 如果审批通过，远程调用接口修改用户角色信息
        if (form.getReviewStatus() == SystemConstant.REVIEW_STATUS_REVIEW_THROUGH) {
            Company company = baseMapper.selectById(form.getCompanyId());
            GraceJSONResult result = userFeignClient.updateUserRole(company.getCommitUserId(), form.getCompanyId());
            // 如果远程修改出现问题，抛出异常回滚事务
            if (result.getStatus() != 200 || !(boolean) result.getData()) {
                GraceException.display(ResponseStatusEnum.USER_ROLE_UPDATE_ERROR);
            }
        }
        return false;
    }

    @Override
    public PagedGridResult queryCompanyList(CompanyQueryForm form) {
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<Company>()
                .likeRight(!form.getCompanyName().isEmpty(), Company::getCompanyName, form.getCompanyName());
        if (!form.getCommitName().isEmpty()) {
            // 远程调用没有使用泛型，返回对象是LinkedHashMap对象，不能直接转换。先转为JSON格式字符串再转回javaBean
            Object object = userFeignClient.userIdList(form.getCommitName()).getData();
            List<Users> userList = JSON.parseArray(JSONUtil.toJsonStr(object), Users.class);
            // 远程调用查询到的结果作为查询参数，如果没有查到提交人需要给一个不存在的提交人ID值
            if (CollUtil.isNotEmpty(userList)) {
                List<String> userIdList = userList.stream().map(Users::getId).collect(Collectors.toList());
                queryWrapper.in(Company::getCommitUserId, userIdList);
            } else {
                queryWrapper.in(Company::getCommitUserId, new ArrayList<>().add("-1"));
            }
        }
        if (form.getStartDateTime() != null) {
            queryWrapper.ge(Company::getCommitDate, form.getStartDateTime());
        }
        if (form.getEndDateTime() != null) {
            queryWrapper.ge(Company::getCommitDate, form.getEndDateTime());
        }
        if (form.getReviewStatus() >= 0 && form.getReviewStatus() <= 3) {
            queryWrapper.eq(Company::getReviewStatus, form.getReviewStatus());
        }
        Page<Company> pageParam = new Page<>(form.getPageIndex(), form.getPageSize());
        baseMapper.selectPage(pageParam, queryWrapper);
        return PagedGridResult.setterPagedGrid(pageParam);
    }

    @Override
    public Company getCompany(String companyName) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Company>().eq(Company::getCompanyName, companyName));
    }

    @Override
    public Company createCompany(CompanyAddOrReviewForm addForm) {
        Company company = BeanUtil.copyProperties(addForm, Company.class);
        company.setReviewStatus(SystemConstant.REVIEW_STATUS_UNREVIEWED);
        company.setIsVip(SystemConstant.IS_NOT_VIP);
        baseMapper.insert(company);
        return company;
    }

    @Override
    public Company reviewCompany(CompanyAddOrReviewForm reviewForm) {
        Company company = baseMapper.selectById(reviewForm.getId());
        company.setReviewStatus(SystemConstant.REVIEW_STATUS_UNREVIEWED);
        company.setReviewReplay("");
        baseMapper.updateById(company);
        return company;
    }

    @Override
    public Company reviewCompanyHr(CompanyHrReviewForm reviewForm) {
        Company company = baseMapper.selectById(reviewForm.getCommitUserId());
        company.setReviewStatus(SystemConstant.REVIEW_STATUS_REVIEW_THROUGH);
        company.setCommitUserId(reviewForm.getCommitUserId());
        company.setCommitUserMobile(reviewForm.getCommitUserPhone());
        company.setAuthLetter(reviewForm.getAuthLetter());
        company.setCommitDate(new Date());
        baseMapper.updateById(company);
        return company;
    }

}
